<template>
  <div>
    <el-dialog title="分配权限" :visible="showDialog" @close="closeFn">
      <el-tree ref="tree" :data="permList" :props="{label:'title'}" default-expand-all node-key="id" show-checkbox check-strictly />
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="confirm">确定</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// 引入所有权限先的接口函数
import { getPermissionList, getPermissionCount } from '@/api/permission'
// 引入获取详情角色的接口函数
import { getRoleDetail, updateRoles } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      limit: 0,
      permList: [],
      permIds: [],
      roleId: ''
    }
  },
  async created() {
    const result = await getPermissionCount()
    this.limit = result.data
    // console.log('获取到的所有权限数量', this.limit)
    // 获取所有权限列表
    const res = await getPermissionList(
      {
        _limit: this.limit,
        _start: 0
      }
    )
    this.permList = this.listToTree(res.data, '0')
    console.log('获取到的所有权限列表', this.permList)
  },
  methods: {
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空数组
      this.permIds = []
      this.$refs.tree.setCheckedKeys(this.permIds)
    },
    // 递归函数
    listToTree(arr, id) {
      const list = []
      arr.forEach(item => {
        // 一级部门
        if (item.pid === '' + id) {
          list.push(item)
          const res = this.listToTree(arr, item.id)
          // console.log(res)
          item.children = res
        }
      })
      return list
    },
    // 获取当前角色权限id
    async getPermIds(id) {
      // 添加加载效果
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)',
        body: true
      })
      const res = await getRoleDetail(id)
      //   console.log('获取到当前角色的默认权限列表,68,', res)
      this.permIds = res.data.permissions
      this.permIds = this.permIds.map(item => {
        return item.id
      })
      this.roleId = id
      //   console.log('获取到当前角色的默认权限列表', this.permIds)
      // 回显
      this.$refs.tree.setCheckedKeys(this.permIds)
      // 请求结束，关闭加载效果
      loading.close()
    },
    // 给角色分配权限
    async confirm() {
      await updateRoles({
        'id': this.roleId,
        'permissions': this.$refs.tree.getCheckedKeys()
      })
      // this.$message.success('分配权限成功！')
      // 关闭弹窗
      this.closeFn()
    }
  }

}
</script>

<style lang="scss">
.el-loading-mask.is-fullscreen{
  z-index: 999999 !important;
}

</style>
